package com.wmx.jdbc_template_app.easypoi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.wmx.jdbc_template_app.utils.ResultData;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 用户信息上传与下载
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2024/5/19 9:18
 */
@RestController
public class EasypoiController {

    private static final Logger log = LoggerFactory.getLogger(EasypoiController.class);

    @Resource
    private User2VerifyHandler userVerifyHandler;

    /**
     * http://localhost:8080/easypoi/exportExcel
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/easypoi/exportExcel")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户列表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<User2VO> listUserExport = listUser2ImportVO(35);
        // 导出参数设置
        // 默认会自动冻结表头;
        // 内容默认自动换行;
        // title：自动在第一行跨所有列然后合并单元格作为一级标题;实体属性上面的注解名称作为第二行开始的二级标题;
        ExportParams exportParams = new ExportParams("用户列表", "用户信息");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User2VO.class, listUserExport);
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }
    }

    /**
     * http://localhost:8080/easypoi/importExcel
     *
     * @param file
     * @return
     */
    @PostMapping("/easypoi/importExcel")
    public ResultData importExcel(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        InputStream inputStream = file != null ? file.getInputStream() : EasypoiController.class.getClassLoader().getResourceAsStream("data/excel/用户列表.xlsx");
        ImportParams importParams = new ImportParams();
        // 表格标题行数,默认0
        importParams.setTitleRows(1);
        // 是否需要校验上传的Excel,默认为false
        importParams.setNeedVerify(true);
        // 默认的校验通常无法满足要求，此时可以自定义的验证器。
        importParams.setVerifyHandler(userVerifyHandler);
        ExcelImportResult<User2VO> excelImportResult = ExcelImportUtil.importExcelMore(inputStream, User2VO.class, importParams);
        if (excelImportResult.isVerifyFail()) {
            for (User2VO vo : excelImportResult.getFailList()) {
                log.error("数据校验未通过：{}", vo);
            }
            return ResultData.error("文档数据校验失败！");
        }
        if (!CollectionUtils.isEmpty(excelImportResult.getList())) {
            for (User2VO vo : excelImportResult.getList()) {
                log.info("导入成功(数据入库)：{}", vo);
            }
        }
        return ResultData.success("导入成功");
    }


    private List<User2VO> listUser2ImportVO(int size) {
        User2VO userExportVO;
        List<User2VO> userExportVOList = new ArrayList<>(size);
        for (int i = 1; i <= size; i++) {
            userExportVO = new User2VO();
            userExportVO.setRealName("千叶真" + i);
            userExportVO.setSex(NumberUtil.isEven(i) ? 2 : 1);
            userExportVO.setBirthday(new Date());
            userExportVO.setPhone(StrUtil.fill(("186" + i), '0', 11, false));
            if (NumberUtil.isEven(new Random().nextInt(10))) {
                userExportVO.setTel(StrUtil.fill(("073" + i), '0', 7, false));
            }
            userExportVO.setEmail(StrUtil.fill(("22" + i + "@qq.com"), '1', 18, true));
            userExportVO.setAvatar("https://img1.baidu.com/it/u=2755104227,3148996602&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800&xx=" + i);
            userExportVOList.add(userExportVO);
        }
        return userExportVOList;
    }

}
